﻿using System.Collections.Generic;
using System.Linq;

namespace Marmat.Forms
{
    public partial class FileManager
    {

        /// <summary>
    /// 保存文件的变更信息。
    /// </summary>
    /// <returns>如果文件全部提交成功，则返回true，否则返回false。</returns>
        public bool SaveChanges()
        {
            bool result = true;
            var files = new List<FileManagerCustomSaveItem>();
            foreach (FileItem item in this.Files.AddCollection)
            {
                if (this.Files.DelCollection.Contains(item) == false)
                {
                    var file = new FileManagerCustomSaveItem(item, FileManagerItemStatusEnum.Add);
                    files.Add(file);
                }
            }

            foreach (FileItem item in this.Files.DelCollection)
            {
                if (this.Files.AddCollection.Contains(item) == false)
                {
                    var file = new FileManagerCustomSaveItem(item, FileManagerItemStatusEnum.Delete);
                    files.Add(file);
                }
            }

            if (files.Count > 0)
            {
                var args = new FileManagerCustomSaveingEventArgs(files.ToArray());
                CustomSaveFileing?.Invoke(this, args);
                if (args.Files.FirstOrDefault(x => !x.Succeed) is object)
                {
                    result = false;
                }

                foreach (var file in files)
                {
                    if (file.Succeed)
                    {
                        if (file.Status == FileManagerItemStatusEnum.Add)
                        {
                            this.Files.AddCollection.Remove(file.Item);
                        }
                        else if (file.Status == FileManagerItemStatusEnum.Delete)
                        {
                            this.Files.DelCollection.Remove(file.Item);
                        }
                    }
                }
            }

            return result;
        }

        protected internal void SetValue()
        {
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(this.Files.list, Newtonsoft.Json.Formatting.None);
            if (this.Files.Count == 0)
            {
                json = null;
            }

            this.Updating = true;
            this.Value = json;
            this.Updating = false;
        }

        public void RaiseBeforeRemoveFile(FileItemCancelEventArgs e)
        {
            BeforeRemoveFile?.Invoke(this, e);
        }
    }
}